package com.example.myapplication42



import android.annotation.SuppressLint
import android.content.res.Configuration
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.cardgame.model.CardMatchingGame
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.GridLayoutManager
import android.app.Activity
import android.content.Intent
//2翻牌游戏
var game: CardMatchingGame = CardMatchingGame(24)
class ThirdActivity : AppCompatActivity() {
    //    lateinit var game: CardMatchingGame //2-状态变
    lateinit var adapter: CardAdapter
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_third)

//        game = CardMatchingGame(24) //2-状态变
        val recyclerView: RecyclerView = findViewById( R.id.recyclerView)
        adapter = CardAdapter(game)
        recyclerView.adapter = adapter

        val configure = resources.configuration
        if (configure.orientation == Configuration.ORIENTATION_PORTRAIT) {
            recyclerView.layoutManager = GridLayoutManager(this,  4)
        } else {
            recyclerView.layoutManager = GridLayoutManager(this,6)
        }
//        recyclerView.layoutManager = GridLayoutManager(this, 4)

        adapter.setOnClickListener {
            game.chooseCardAtIndex(it,2)
            updateUI()
        }
        //把 CardMatchingGame作为数据源, CardAdapter负责 UI 展示, 通过回调通知 Activity 用户点击了
        updateUI()
        val reset = findViewById<Button>( R.id.button_reset)

        reset.setOnClickListener {
            game.reset()
            updateUI()
        }
        val backButton = findViewById<Button>(R.id.button_back)
        backButton?.setOnClickListener {
            val returnIntent = Intent()
            returnIntent.putExtra("SCORE", game.score.toString())
            setResult(Activity.RESULT_OK, returnIntent)
            finish()
        }

    }

    fun updateUI() {
        adapter.notifyDataSetChanged()
        val score = findViewById<TextView>( R.id.textView)
        score.text = getString(R.string.score) + game.score.toString()
    }
}